package com.example.howard.mytcpclient;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class ClientThread implements Runnable {
    //设置TAG名字，为Debug
    private final String TAG = "ClientThread";
    //初始化必要值
    private Socket socket;
    private String ip;
    private int port;
    private Handler receiveHandler;
    public Handler sendHandler;
    //获得客户端列表的Handler
    public Handler sendclientHand;

    private InputStream inputStream;
    private OutputStream outputStream;
    public boolean isConnect = false;
    public String name;
    public String text;
    private List<String> ClientList=new ArrayList<>();
    //回传客户列表的值
    private ClientList clientList;
    //发送消息的键值，在MainActivity中使用接受
    private final static int SEND_MSG_SHOW = 123;
    private MyApplication myApplication;
    public ClientThread(String ip, String port) {
        // TODO Auto-generated constructor stub
        this.ip = ip;
        this.port = Integer.valueOf(port);
        sendclientHand = new Handler(Looper.getMainLooper());

//        clientList=new ClientList();


        Log.d(TAG, "ClientThread's construct is OK!!");

    }

    public void getClientList (ClientList client){
        this.clientList=client;

    }
    //设置接受Handler
    public void setReceiveHandler(Handler receiveHandler) {

        this.receiveHandler = receiveHandler;

    }

    //断开线程
    public void disconnect() {

        if (null != socket && socket.isConnected()) {

            try {
                socket.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void showdisconncet(){
        AllBean allBean = new AllBean();
        allBean.setName("Howard");
        allBean.setText("Client is disconnect !");
        //将JSON转化成字符串
        String content = JSONObject.toJSONString(allBean);
        //通过输出通道将字符串发送出去
        try {
            outputStream.write(content.getBytes());
            outputStream.flush();
            Log.d(TAG,"been disconnect");
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
            e.printStackTrace();
        }
    }

    //线程自动运行内容
    public void run() {
        try {
            Log.d(TAG, "Into the run()");

            socket = new Socket(ip, port);
            isConnect = socket.isConnected();
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();

            //连接后自动发送一次消息
            if (isConnect) {
                //对JSON进行赋值
                AllBean allBean = new AllBean();
                allBean.setName("Howard");
                allBean.setText("The first connect !");
                //将JSON转化成字符串
                String content = JSONObject.toJSONString(allBean);
                //通过输出通道将字符串发送出去
                try {
                    outputStream.write(content.getBytes());
                    outputStream.flush();
                } catch (Exception e) {
                    Log.d(TAG, e.getMessage());
                    e.printStackTrace();
                }
            }


            new Thread() {
                @Override
                public void run() {

                    Log.d(TAG, ip + port);
                    try {
                        byte[] buffer = new byte[1024];
                        //如果socket连接着且输入通道正常
                        while (socket.isConnected() & inputStream.read() != -1) {

                            int readSize = inputStream.read(buffer);
                            String buf = inputStream.toString();
                            Log.d(TAG, "readSize:" + readSize);

                            //如果服务停止了
                            if (readSize == -1) {
                                inputStream.close();
                                outputStream.close();
                            }
                            if (readSize == 0) continue;
                            //如果接受的Handler不为空
                            if (null != receiveHandler) {
                                String s;
                                s = new String(buffer, 0, readSize);
                                //判断是否为客户端列表
                                AllBean ClientBean = JSONObject.parseObject("{"+s,AllBean.class);
//                                AllBean ClientBean = JSONObject.parseObject(s,AllBean.class);
                                if (ClientBean.getName().equals("Client"))
                                {

                                    Message message =new Message();
                                    message.what=0x888;
                                    message.obj=ClientBean.getText();
                                    clientList.clientShowHandler.sendMessage(message);
                                    Log.d(TAG,"receive client item");
                                }else {

                                    //将消息显示在MainActivity
                                    Message msg = new Message();
                                    msg.what = SEND_MSG_SHOW;
                                    msg.obj = "{" + s;
                                    receiveHandler.sendMessage(msg);
                                    Log.d(TAG, "send msg to MainActivity");
                                }
                            }

                        }
                        //服务端提出客户端的响应
                        Log.d(TAG, "first");

                        inputStream.close();
                        outputStream.close();
                        myApplication.keyname=true;



                    } catch (IOException e) {
                        Log.d(TAG, e.getMessage());
                        e.printStackTrace();
                    }
                }

            }.start();

            //发送消息到客户端
            Looper.prepare();
            sendHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case 0x852:
                        AllBean sendBean = new AllBean();
                        sendBean.setName("Howard");
                        sendBean.setText(msg.obj.toString());
                        //将JSON结构转换成字符串
                        String message = JSONObject.toJSONString(sendBean);
                        try {
                            outputStream.write(message.getBytes());
                            outputStream.flush();
                        } catch (Exception e) {
                            Log.d(TAG, e.getMessage());
                            e.printStackTrace();
                        }
                        case 0x853:
                            Log.d(TAG,"reseive client");
                        AllBean resBean = new AllBean();
                            resBean.setName("Howard");
                            resBean.setText(msg.obj.toString());
                            String messageclient = JSONObject.toJSONString(resBean);
                            try {
                                outputStream.write(messageclient.getBytes());
                                outputStream.flush();
                            } catch (Exception e) {
                                Log.d(TAG, e.getMessage());
                                e.printStackTrace();
                            }
                    }
                }
            };
            Looper.loop();

        } catch (SocketTimeoutException e) {
            // TODO Auto-generated catch block
            Log.d(TAG, e.getMessage());
            e.printStackTrace();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            Log.d(TAG, e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.d(TAG, e.getMessage());
            e.printStackTrace();
        }
        sendclientHand = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {

                        case 0x853:

                        AllBean resBean = new AllBean();
                            resBean.setName("Howard");
                            resBean.setName(msg.obj.toString());
                            String messageclient = JSONObject.toJSONString(resBean);
                            try {
                                outputStream.write(messageclient.getBytes());
                                outputStream.flush();
                            } catch (Exception e) {
                                Log.d(TAG, e.getMessage());
                                e.printStackTrace();
                            }
                }
            }
        };

    }


}
